package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

//实现文件的下载
func main() {
	url := "https://tse1-mm.cn.bing.net/th/id/OIP-C.umundCoLai2T9iMnuQqO2QHaHb?w=197&h=198&c=7&r=0&o=5&dpr=1.24&pid=1.7"
	filname := "tupian.jpg"
	// w, result := downloadSource(url, filname)
	// if result {
	// 	fmt.Println("下载成功 w = ", w)
	// } else {
	// 	fmt.Println("下载失败")
	// }
	DownloadProgress(url, filname)
}

//下载文件
func downLoadFile(url, filename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = r.Body.Close()
	}()

	f, err2 := os.Create(filename)
	if err2 != nil {
		panic(err2)
	}
	defer func() {
		_ = f.Close()
	}()

	written, err3 := io.Copy(f, r.Body)
	if err3 != nil {
		panic(err3)
	}
	fmt.Println(written, err)
}

type Reader struct {
	io.Reader
	Total   int64
	Current int64
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.Current += int64(n)
	fmt.Printf("进度: %.2f%%\n", float64(r.Current*10000/r.Total)/100)

	return
}
func DownloadProgress(url, filename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = r.Body.Close()
	}()

	f, err2 := os.Create(filename)
	if err2 != nil {
		panic(err2)
	}
	defer func() {
		_ = f.Close()
	}()

	reader := &Reader{
		Reader: r.Body,
		Total:  r.ContentLength,
	}
	written, err3 := io.Copy(f, reader)
	if err3 != nil {
		panic(err3)
	}
	fmt.Println(written, err)
}

//自定义下载器
func downloadSource(url, filename string) (w int64, result bool) {
	result = true
	r, err := http.Get(url)
	if err != nil {
		result = false
		panic(err)
	}
	defer func() {
		_ = r.Body.Close()
	}()
	//创建文件接收
	f, err2 := os.Create(filename)
	if err2 != nil {
		result = false
		panic(err2)
	}
	defer f.Close()
	//使用io.copy将目标资源传入目标文件
	written, err3 := io.Copy(f, r.Body)
	if err3 != nil {
		result = false
		panic(err3)
	}
	return written, true
}
